<?php namespace app\service\controller;

require("../vendor/qiniu/autoload.php");
use think\Controller;

/**
 * 微信小程序支付服务层
 */
class WechatAppletPay extends Controller{
	
	private $appid = '';			//小程序appid
	private $secret = '';			//小程序密钥
	private $mchId = '';			//微信支付商户号
	private $signType = '';			//微信支付加密类型
	private $apiv2 = '';			//微信支付APIv2加密串
	
	private $url = [
		'unifiedorder'	=>	'https://api.mch.weixin.qq.com/pay/unifiedorder',		//统一下单
		'callbackUrl'	=>	'/callback/wechatAppletCallback',							//支付回调路径
	];
	
	public function __construct(){
		parent::__construct();
		$this -> url['callbackUrl'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $this -> url['callbackUrl'];
		if( empty($this -> appid) ){
			$wechatCof = config('WECHAT_MIN');
			$this -> appid = $wechatCof['APPID'];
			$this -> secret = $wechatCof['SECRET'];
		}
		if( empty($this -> mchId) ){
			$wechatApyCof = config('WECHAT_PAY');
			$this -> mchId = $wechatApyCof['MCH_ID'];
			$this -> signType = $wechatApyCof['SIGN_TYPE'];
			$this -> apiv2 = $wechatApyCof['API_V2'];
		}
	}
	
	/**
	 * 统一下单
	 * @param	array	$data		
	 * @return	array
	 */
	public function unifiedorder($data = []){
		
		$param['appid'] = $this -> appid;										//小程序appid
		$param['mch_id'] = $this -> mchId;										//微信支付商户号
		$param['nonce_str'] = strval(time()) . strval(rand(10000, 99999));		//随机字符串
		$param['body'] = $data['body'];											//商品描述
		$param['out_trade_no'] = $data['outTradeNo'];							//商户订单号
		$param['total_fee'] = $data['totalFee'];								//标价金额(分)
		$param['spbill_create_ip'] = getIP();									//终端ip
		$param['notify_url'] = $this -> url['callbackUrl'];						//通知地址
		$param['trade_type'] = 'JSAPI';											//交易类型
		$param['openid'] = $data['openId'];										//openId
		$param['attach'] = $data['attach'];										//openId
		ksort($param);
		
		$param['sign'] = $this -> getSign($param);
		
		$paramXML = arrayToXml($param);
		
		$url = $this -> url['unifiedorder'];
		
		$re = requestPost($url, $paramXML);
		$re = json_decode(json_encode(simplexml_load_string($re,'SimpleXMLElement',LIBXML_NOCDATA)),TRUE);
		
		if( $re['return_msg'] != 'OK' ){
			$outArr['code'] = '50003';
		}else{
			$outArr['code'] = '1';
		}
		$outArr['info'] = $re;
		return $outArr;
	}
	
	/**
	 * 签名
	 */
	private function getSign($param = []){
		$param = formUrlencoded($param);
		$param .= '&key=' . $this -> apiv2;
		switch ($this -> signType) {
			case 'MD5': return strtoupper(md5($param)); break;
			default: return FALSE; break;
		}
	}
	
}
